#include<stdio.h>
#include "../include/vfs.h"
#include<stdlib.h>
#include<string.h>


int updatefile(char path[], char file_path[])
{

	FILE *fp,*add;
	char *data,ch,*tok;
	int saveblock,i,recsize,k=0,flag=1,pos;
	
	FD *fd;
	Block *b;
	
	fd=(FD*)malloc(sizeof(FD));
	strcpy(fd->path,path);

	b=malloc(sizeof(Block));

	fp = fopen(filesystem_name,"r+b");

	header=malloc(sizeof(Header));

	fread(header,sizeof(Header),1,fp);

	add = fopen(file_path,"r");

	if(add==NULL)
		return 1;

	data = malloc(1024*sizeof(char));

	fseek(add,0,SEEK_END);
	pos = ftell(add);

	if(pos>1024)
		return 5;

	rewind(add);

    	while (1)
    	{	
		ch=fgetc(add);
		if(ch==EOF)
		break;
		data[k]=ch;
		k++;
	}

		fd = search(roots.naryroot,fd);

		if(fd==NULL)
		{
			
			return 2;
		}
		
		if(fd->file_type==0)
			return 2;

		else
		{

			saveblock=fd->block_no;
	
			recsize=sizeof(Block);
	
			
			while(i<header->max_FD && flag)
			{
				fread(b,sizeof(Block),1,fp);
			
				if (b->num==saveblock)					
				{

					strcpy(b->buffer,data);
					//printf("\n \n DATA:%s\n \n",b->buffer);

					fseek(fp,(-(1*recsize)),SEEK_CUR);
					fwrite(b,sizeof(Block),1,fp);
					
					flag=0;
				}
				i++;
			}
		}	

		rewind(fp);

		fwrite(header,sizeof(Header),1,fp);

		fclose(fp);

	return 0;

}

















